//
//  HBBaseReadController.m
//  HeartBeat
//
//  Created by karong on 2023/9/12.
//

#import "HBBaseReadController.h"
#import "HBReadManageView.h"
#import "HBReadSettingManager.h"
#import "HBReadSubController.h"
#import "HBReadCoverController.h"
#import "NSDate+Time.h"
#import "HBReadCoverView.h"
#import "HBPayController.h"
#import "HBVipController.h"

@interface HBBaseReadController () <UIGestureRecognizerDelegate, HBReadBottomViewDelegate, HBReadSettingViewDelegate, UIPageViewControllerDelegate, UIPageViewControllerDataSource, PPReadCoverViewDelegate, PPReadSuDelegate, HBReadManageViewDelegate, HBPayControllerDelegate, HBVipControllerDelegate>
@property (strong, nonatomic) HBReadManageView *mangerView;
@property (assign, nonatomic) BOOL clickPageCtrl;               ///是否点击默认pageCtrl
@property (assign, nonatomic) BOOL pagecurl;
@property (strong, nonatomic) UIPageViewController *pageCtrl;
@property (strong, nonatomic) HBReadCoverController *pageCoverCtrl;
@property (nonatomic, strong) HBNovelModel * novelModel;
@property (nonatomic, strong) HBChapterModel * chapterModel;
@property (assign, nonatomic) NSInteger chapter;                ///实际章节下标
@property (strong, nonatomic) NSMutableArray *chapterArr;       ///章节s数组
@property (assign, nonatomic) NSInteger chapterIndex;           ///当前章节在章节数组中的下表
@property (nonatomic, strong) HBReadCoverView * 封面;
@property (nonatomic, strong) HBPayController * 解锁弹窗;
@property (nonatomic, strong) HBVipController * VIP弹窗;
@property (nonatomic, assign) BOOL needReload;
@end

@implementation HBBaseReadController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.needReload) {
        self.needReload = NO;
        [self loadChapterDetailWithID:self.chapterModel.id lineNum:0 hasFirst:NO];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    self.view.backgroundColor = UIColor.font_white_ffffff;
    [self removeViewControllerAtNavigationControllers];
    [self loadUI];
    [self loadDetailData:YES];
    [self addObserver];
}

- (void)addObserver {
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(needReloadData) name:HBRefreshChapterNotification object:nil];
}

- (void)needReloadData {
    self.needReload = YES;
}

// 删除其他重复视图
- (void)removeViewControllerAtNavigationControllers {
    NSMutableArray *array = self.navigationController.viewControllers.mutableCopy;
    for (UIViewController *item in self.navigationController.viewControllers) {
        NSString *itemClassName = NSStringFromClass(item.class);
        if ([itemClassName isEqualToString:@"HBBaseReadController"] && item != self) {
            [array removeObject:item];
        }
    }
    self.navigationController.viewControllers = array;
}

- (void)addFollowRequest {
    self.novelModel.chapter_id = self.chapterModel.id;
    self.novelModel.had_read = 1;;
    [HBRequest addBookshelfWithAddArray:@[self.novelModel] success:^{
        [self.navigationController popViewControllerAnimated:YES];
    } failed:^(NSURLResponse *response, NSError *error, id responseObject) {
        
    }];
}

- (void)addReadLogRequest:(HBChapterModel *)chapter {
    [HBRequest addReadLogWithChapter_id:chapter.id success:^{
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
    }];
}

- (void)reloadMainData{
    [self loadChapterDetailWithID:self.chapterModel.id lineNum:0 hasFirst:YES];
}

- (void)payRequest:(HBChapterModel *)chapter isAuto:(BOOL)isAuto {
    WeakSelf
    [HBToast loadingFull];
    [HBRequest payChapterWithChapter_id:chapter.id success:^{
        [HBToast dismiss];
        [weakSelf removePayAlter];
        [weakSelf loadChapterDetailWithID:chapter.id lineNum:0 hasFirst:NO];
        if (isAuto) {
            [HBEvenManager event:@"auto_purchase" evenLogType:(HBEvenLogType_Click) attributes:@{@"is_success":@"ture"}];
        }
        else {
            [HBEvenManager event:@"chapter_purchase" evenLogType:(HBEvenLogType_Click) attributes:@{@"is_success":@"ture"}];
        }
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        if (isAuto) {
            [HBEvenManager event:@"auto_purchase" evenLogType:(HBEvenLogType_Click) attributes:@{@"is_success":@"false"}];
        }
        else {
            [HBEvenManager event:@"chapter_purchase" evenLogType:(HBEvenLogType_Click) attributes:@{@"is_success":@"false"}];
        }
        for (HBChapterModel *subM in self.chapterArr) {
            if (subM.id == self.chapterModel.id) {
                self.chapterModel = subM;
                [self reloadData];
                break;
            }
        }
    }];
}

- (void)prepayRequest:(HBChapterModel *)chapter {
    WeakSelf
    [HBRequest payChapterWithChapter_id:chapter.id success:^{
        [weakSelf prestrainLoadChapter:chapter];
        [HBEvenManager event:@"auto_purchase" evenLogType:(HBEvenLogType_Click) attributes:@{@"is_success":@"ture"}];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        [HBEvenManager event:@"auto_purchase" evenLogType:(HBEvenLogType_Click) attributes:@{@"is_success":@"false"}];
    }];
}


- (void)packagePayRequest:(HBChapterModel *)chapter num:(NSInteger)num {
    WeakSelf
    [HBToast loadingFull];
    [HBRequest packageWithChapter_id:chapter.id num:num  success:^{
        [HBToast dismiss];
        [weakSelf removePayAlter];
        [weakSelf loadChapterDetailWithID:chapter.id lineNum:0 hasFirst:NO];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        weakSelf.chapterModel = chapter;
        weakSelf.pageIndex = 0;
        [weakSelf reloadPageUI];
    }];
}
///加载书籍详情
- (void)loadDetailData:(BOOL)hasReload{
    [HBRequest loadNovelDetailWithId:self.novelID success:^(id obj) {
        self.novelModel = obj;
        self.mangerView.enumView.hasBookShelf = self.novelModel.is_bookshelf;        
        if (hasReload) {
            if (self.chapterID < 1) {
                self.chapterID = self.novelModel.id;
            }
            [self loadChapterDetailWithID:self.chapterID lineNum:self.pageIndex hasFirst:YES];
        }
    } failed:^(NSURLResponse *response, NSError *error, id responseObject) {
        
    }];
}

///加载章节详情
- (void)loadChapterDetailWithID:(NSInteger)cID lineNum:(NSUInteger)lineNum hasFirst:(BOOL)hasFirst{
    [self.chapterArr removeAllObjects];
    self.chapterArr = [NSMutableArray new];
    self.chapterIndex = 0;
    [HBRequest loadChapterDetailWithChapter_id:cID success:^(id obj) {
        [self createData:obj lineNum:lineNum hasFirst:hasFirst];
    } failed:^(NSURLResponse *response, NSError *error, id responseObject) {
        
    }];
}

///书籍加载成功后的创建数据
- (void)createData:(HBChapterModel *)result lineNum:(NSUInteger)lineNum hasFirst:(BOOL)hasFirst{
    [result setContentPage];
    [self.chapterArr addObject:result];
    if (result.sort > 0) {
        self.chapter = result.sort - 1;
    }else{
        self.chapter = result.sort;
    }

    if (hasFirst) {
        if (self.chapter == 0 && self.pageIndex == 0) {
            [self createFengMianView];
        }
        [self 添加引导];
    }
    self.chapterModel = result;
    [self.chapterModel setContentPage];
    self.pageIndex = lineNum;
    [self reloadData];
    
    ///预加载数据
    if (result.next_chapter_id > 0) {
        [self prestrainLoadChapter:NO andCID:result.next_chapter_id];
    }
    if (result.pre_chapter_id > 0) {
        [self prestrainLoadChapter:YES andCID:result.pre_chapter_id];
    }
}

///预加载上一章和下一章数据  ifLast是否上一章
- (void)prestrainLoadChapter:(BOOL)ifLast andCID:(NSInteger)cID {
    [HBRequest loadChapterDetailWithChapter_id:cID success:^(HBChapterModel * obj) {
        [obj setContentPage];
        if (ifLast) {
            [self.chapterArr insertObject:obj atIndex:0];
        }else{
            [self.chapterArr addObject:obj];
            ///判断是否自动解锁
            [self checkAutoPay:obj];
        }
    } failed:^(NSURLResponse *response, NSError *error, id responseObject) {
        
    }];
}

///
- (void)prestrainLoadChapter:(HBChapterModel *)chapter {
    [HBRequest loadChapterDetailWithChapter_id:chapter.id success:^(HBChapterModel * obj) {
        [obj setContentPage];
        obj.needToastAotuPay = YES;
        if ([self.chapterArr containsObject:chapter]) {
            [self.chapterArr replaceObjectAtIndex:[self.chapterArr indexOfObject:chapter] withObject:obj];
        }
        if (chapter.id == self.chapterModel.id) {
            [self reloadData];
        }
    } failed:^(NSURLResponse *response, NSError *error, id responseObject) {
        
    }];
}

- (void)reloadData {
    [self reloadUI];
    [self.mangerView.enumView setContentDataWithShowModel:self.chapterModel];
    [self.mangerView.navView createMainDataWithDataModel:self.chapterModel];
}

- (void)reloadUI{
    self.pagecurl ? [self reloadPageUI] : [self reloadCover];
}

- (void)reloadPageUI{
    UIViewController *vc = [self getReadCotroller];
    [self.pageCtrl setViewControllers:@[vc]
                            direction:UIPageViewControllerNavigationDirectionForward
                             animated:NO
                           completion:nil];
}

- (void)reloadCover{
    UIViewController *vc = [self getReadCotroller];
    [self.pageCoverCtrl setController:vc];
}

///获取当前页
- (HBReadSubController *)getReadCotroller{
    HBReadSubController *vc = (HBReadSubController *)[ViewManager readSubControllerVC];
    vc.delegate = self;
    [vc setModel:self.chapterModel chapter:self.chapter pageIndex:self.pageIndex];
    return vc;
}

/// 添加封面view
- (void)createFengMianView{
    HBReadCoverView *feng = [[[NSBundle mainBundle] loadNibNamed:@"HBReadCoverView" owner:self options:nil] firstObject];
    feng.frame = CGRectMake(0, 0, HBScreenWidth, HBScreenHeight);
    [feng createContentDataWithDataModel:self.novelModel];
    self.封面 = feng;
    [self.view insertSubview:feng aboveSubview:self.mangerView];
}

/// 添加引导view
- (void)添加引导{
    if (!appConfig.hasReadGuide) {
        appConfig.hasReadGuide = YES;
        [ViewManager showReadGuideVCInController:self];
    }
}

- (void)loadUI{
    [self.view addSubview:self.mangerView];
    self.pagecurl ? [self loadPageUI] : [self loadCoverUI];
}

- (void)loadPageUI{
    [self removeCoverCtrl];
    [self removePageCtrl];
    HBReadSettingModel *model = [HBReadSettingManager.shared showModel];
    UIPageViewControllerTransitionStyle style = UIPageViewControllerTransitionStyleScroll;
    UIPageViewControllerNavigationOrientation orien = UIPageViewControllerNavigationOrientationVertical;
    if (model.browseState == HBBrowseType_None) {
        orien = UIPageViewControllerNavigationOrientationHorizontal;
    }
    self.pageCtrl = [[UIPageViewController alloc] initWithTransitionStyle:style navigationOrientation:orien options:nil];
    UIViewController *vc = [ViewManager readSubControllerVC];
    [self.pageCtrl setViewControllers:@[vc]
                            direction:UIPageViewControllerNavigationDirectionForward
                             animated:NO
                           completion:nil];
    switch (model.browseState) {
        case HBBrowseType_Scroll:
        case HBBrowseType_None:
            self.pageCtrl.dataSource = self;
            self.pageCtrl.delegate = self;
            break;
        default:
            
            break;
    }
    
    [self addChildViewController:self.pageCtrl];
    [self.view addSubview:self.pageCtrl.view];
    [self.view sendSubviewToBack:self.pageCtrl.view];
    [self.pageCtrl.view mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.pageCtrl.view.superview);
    }];
    [self.pageCtrl didMoveToParentViewController:self];
}

- (void)loadCoverUI{
    [self removeCoverCtrl];
    [self removePageCtrl];
    HBReadSettingModel *model = [HBReadSettingManager.shared showModel];
    self.pageCoverCtrl = [[HBReadCoverController alloc] init];
    UIViewController *vc = [[HBReadSubController alloc] init];
    [self.pageCoverCtrl setController:vc];
    self.pageCoverCtrl.delegate = self;
    [self addChildViewController:self.pageCoverCtrl];
    [self.view addSubview:self.pageCoverCtrl.view];
    [self.view sendSubviewToBack:self.pageCoverCtrl.view];
    [self.pageCoverCtrl.view mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.pageCoverCtrl.view.superview);
    }];
    [self.pageCoverCtrl didMoveToParentViewController:self];
    self.pageCoverCtrl.openAnimate = model.browseState == HBBrowseType_Cover ? YES : NO;
}

- (void)removeCoverCtrl{
    if (_pageCoverCtrl) {
        [_pageCoverCtrl.view removeFromSuperview];
        [_pageCoverCtrl removeFromParentViewController];
        _pageCoverCtrl.delegate = nil;
        _pageCoverCtrl = nil;
    }
}

- (void)removePageCtrl{
    if (_pageCtrl) {
        [_pageCtrl.view removeFromSuperview];
        [_pageCtrl removeFromParentViewController];
        _pageCtrl.dataSource = nil;
        _pageCtrl.delegate = nil;
        _pageCtrl = nil;
    }
}
#pragma mark buttonAction手势点击
- (void)tapAction:(UITapGestureRecognizer *)sender {
    CGPoint point = [sender locationInView:self.view];

    CGFloat width = self.view.width / 3;
    CGFloat height = self.view.height;
    CGRect centerFrame = CGRectMake(width, 0, width, height);
    if (CGRectContainsPoint(centerFrame, point)) {
        [self centerAction];
    }
    else if (point.x >= self.view.width * 2 / 3) {
        if (self.nonecurl) {
            if (!self.clickPageCtrl) {
                [self rightAction];
            }
            self.clickPageCtrl = NO;
        }
    }
    else {
        if (self.nonecurl) {
            if (!self.clickPageCtrl) {
                [self leftAction];
            }
            self.clickPageCtrl = NO;
            ///如果第一章第一页，点击添加封面
            if (self.pageIndex <= 0 && self.chapter <= 0) {
                [self createFengMianView];
            }
        }
    }
}

- (void)leftAction{
    UIViewController *vc = [self beforeController];
    if (vc) {
        [self.pageCtrl setViewControllers:@[vc]
                                direction:UIPageViewControllerNavigationDirectionForward
                                 animated:NO
                               completion:nil];
    }
}

- (void)rightAction{
    UIViewController *vc = [self afterController];
    if (vc) {
        [self.pageCtrl setViewControllers:@[vc]
                                direction:UIPageViewControllerNavigationDirectionForward
                                 animated:NO
                               completion:nil];
    }
}

- (void)centerAction{
    [self.mangerView clickTapBtn];
}

- (BOOL)pagecurl{
    HBReadSettingModel *model = [[HBReadSettingManager shared] showModel];
    return model.browseState == HBBrowseType_Scroll || model.browseState == HBBrowseType_None;
}

- (BOOL)nonecurl{
    HBReadSettingModel *model = [[HBReadSettingManager shared] showModel];
    return model.browseState == HBBrowseType_Scroll || model.browseState == HBBrowseType_None;
}
///获取上一页
- (HBReadSubController *)beforeController{
    if (self.pageIndex <= 0 &&self.chapter <= 0) {
        return nil;
    }else if (self.pageIndex <= 0){
        HBReadSubController *vc = self.pagecurl ? self.pageCtrl.viewControllers.firstObject : (HBReadSubController *)self.pageCoverCtrl.currentController;
        if (vc.chapter == self.chapter) {
            self.chapter -- ;
            [self getchapterModel:self.chapter hasNext:NO];
            self.pageIndex = self.chapterModel.pageCount-1;
        }
        return [self getReadCotroller];
    }else{
        HBReadSubController *vc = self.pagecurl ? self.pageCtrl.viewControllers.firstObject : (HBReadSubController *)self.pageCoverCtrl.currentController;
        if (vc.pageIndex == self.pageIndex) {
            self.pageIndex -- ;
        }
        return [self getReadCotroller];
    }
}

///获取下一页
- (HBReadSubController *)afterController{
    if (self.pageIndex >= self.chapterModel.pageCount-1 && self.chapterModel.next_chapter_id < 1){
//        [self pushEndVC];
        return nil;
    }else if (self.pageIndex >= self.chapterModel.pageCount-1){
        HBReadSubController *vc = self.pagecurl ? self.pageCtrl.viewControllers.firstObject : (HBReadSubController *)self.pageCoverCtrl.currentController;
        if (vc.chapter == self.chapter) {
            self.chapter ++ ;
            [self getchapterModel:self.chapter hasNext:YES];
            self.pageIndex = 0;
        }
        return [self getReadCotroller];
    }else{
        HBReadSubController *vc = self.pagecurl ? self.pageCtrl.viewControllers.firstObject : (HBReadSubController *)self.pageCoverCtrl.currentController;
        if (vc.pageIndex == self.pageIndex) {
            self.pageIndex ++ ;
        }
        return [self getReadCotroller];
    }
}

- (void)getchapterModel:(NSInteger)chapter hasNext:(BOOL)hasNext{
    if (hasNext) {
        [self showChapterData:NO];
    }else{
        [self showChapterData:YES];
    }
}

///展示当前章节数据
- (void)showChapterData:(BOOL)ifLast{
    NSInteger index = 0;
    for (int x = 0; x < self.chapterArr.count; x++) {
        HBChapterModel * model = self.chapterArr[x];
        if (model.id == self.chapterModel.id) {
            if (x == 0 && model.pre_chapter_id > 0) {
                index = 1;
            }
            if (model == self.chapterArr.lastObject && model.next_chapter_id > 0) {
                index = x - 1;
            }
            else {
                index = x;
            }
            index = x;
            break;
        }
    }
    if (ifLast && index > 0) {
        if (self.chapterArr.count > index-1) {
            HBChapterModel * model = self.chapterArr[index-1];
            self.pageIndex = model.pageCount-1;
            self.chapterModel = model;
            [self.chapterModel setContentPage];
//            [self reloadData];
            if (self.chapterModel.pre_chapter_id > 0) {
                BOOL hasSave = NO;
                ///判断数组中是否已存在上一章
                for (HBChapterModel *subM in self.chapterArr) {
                    if (subM.id == self.chapterModel.pre_chapter_id) {
                        hasSave = YES;
                    }
                }
                if (!hasSave) {
                    [self prestrainLoadChapter:YES andCID:self.chapterModel.pre_chapter_id];
                }
            }
        }
    }else if (!ifLast && self.chapterArr.count > index+1){
        HBChapterModel * model = self.chapterArr[index+1];
        self.pageIndex = 0;
        self.chapterModel = model;
        [self.chapterModel setContentPage];
        if (self.chapterModel.next_chapter_id > 0) {
            BOOL hasSave = NO;
            ///判断数组中是否已存在下一章
            for (HBChapterModel *subM in self.chapterArr) {
                if (subM.id == self.chapterModel.next_chapter_id) {
                    hasSave = YES;
                    ///判断是否自动解锁
                    [self checkAutoPay:subM];
                }
            }
            if (!hasSave) {
                [self prestrainLoadChapter:NO andCID:self.chapterModel.next_chapter_id];
            }
        }
    }else if(!ifLast) {
        [self loadChapterDetailWithID:self.chapterModel.next_chapter_id lineNum:0 hasFirst:NO];
    }
}
///尾页
- (void)pushEndVC{
    [ViewManager pushReadEndVCWithNovel:self.novelModel inController:self];
}

- (void)resetDataView:(BOOL)fullscreen {
    NSArray *datas = [self.chapterModel positionDatas];
    NSNumber *position= [datas objectAtIndex:self.pageIndex];
    [self.chapterModel setContentPage];
    self.pageIndex = [self.chapterModel getChangeIndex:position];
    [self reloadUI];
}

- (void)backAction {
    if (self.novelModel.is_bookshelf) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else {
        [ViewManager showAlterWithTitle:WSLocalized(@"是否加入書架") content:WSLocalized(@"加書架才會收到更新提醒哦~") confirm:WSLocalized(@"加入書架") confirmHandle:^{
            [self addFollowRequest];
            [HBEvenManager event:@"shelf_add" evenLogType:(HBEvenLogType_Click)
                      attributes:@{@"type_selection":@"3"}];
        } cancel:WSLocalized(@"再想想") cancelHandle:^{
            [self.navigationController popViewControllerAnimated:YES];
        } inController:self];
        [HBEvenManager event:@"shelf_add" evenLogType:(HBEvenLogType_Pop)
                  attributes:@{@"type_selection":@"1"}];
    }
}


- (void)setChapterModel:(HBChapterModel *)chapterModel {
    _chapterModel = chapterModel;
    [self addReadLogRequest:chapterModel];
    [self checkChapterPayStatus:chapterModel];
    [self.mangerView.enumView setContentDataWithShowModel:chapterModel];
    [self.mangerView.navView createMainDataWithDataModel:chapterModel];
    if (chapterModel.needToastAotuPay) {
        chapterModel.needToastAotuPay = NO;
        [HBToast simple:WSLocalized(@"已為您自動解鎖該章節")];
    }
}

///檢查是否需要解鎖
- (void)checkChapterPayStatus:(HBChapterModel *)chapterModel {
    [self removePayAlter];
    if (chapterModel.need_buy) {
        if (self.novelModel.is_vip) {
            [self showVipAlter:chapterModel];
        }
        else {
            [self showPayAlter:chapterModel];
        }
    }
}

///檢查是否自动解鎖
- (void)checkAutoPay:(HBChapterModel *)chapter {
    if (chapter.need_buy && !self.novelModel.is_vip && appConfig.isAutoPay && appUserCenter.coins >= chapter.coins) {
        [self prepayRequest:chapter];
    }
}

//顯示支付頁面
- (void)showPayAlter:(HBChapterModel *)chapter {
    if (appConfig.isAutoPay && appUserCenter.coins >= chapter.coins) {
        [self payRequest:chapter isAuto:YES];
        [HBToast simple:WSLocalized(@"已為您自動解鎖該章節")];
        [HBEvenManager event:@"auto_purchase" evenLogType:(HBEvenLogType_Click)];
    }
    else {
        self.解锁弹窗 = [ViewManager payVC];
        self.解锁弹窗.novel = self.novelModel;
        self.解锁弹窗.chapter = self.chapterModel;
        self.解锁弹窗.delegate = self;
        [self.view insertSubview:self.解锁弹窗.view belowSubview:self.mangerView];
        [self addChildViewController:self.解锁弹窗];
        [self.解锁弹窗.view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.left.right.mas_equalTo(self.view);
            make.height.mas_equalTo(324);
        }];
    }
}

- (void)showVipAlter:(HBChapterModel *)chapter {
    self.VIP弹窗 = [ViewManager vipVC];
    self.VIP弹窗.novel = self.novelModel;
    self.VIP弹窗.chapter = self.chapterModel;
    self.VIP弹窗.delegate = self;
    [self.view insertSubview:self.VIP弹窗.view belowSubview:self.mangerView];
//    [self.view bringSubviewToFront:self.VIP弹窗.view];
    [self addChildViewController:self.VIP弹窗];
    [self.VIP弹窗.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.mas_equalTo(self.view);
        make.height.mas_equalTo(278);
    }];
}
///移除支付頁面
- (void)removePayAlter {
    if (self.解锁弹窗) {
        [self.解锁弹窗 removeFromParentViewController];
        [self.解锁弹窗.view removeFromSuperview];
        self.解锁弹窗 = nil;
    }
    if (self.VIP弹窗) {
        [self.VIP弹窗 removeFromParentViewController];
        [self.VIP弹窗.view removeFromSuperview];
        self.VIP弹窗 = nil;
    }
}
#pragma mark - UIPageViewControllerDelegate,UIPageViewControllerDataSource
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(HBReadSubController *)viewController {
    self.clickPageCtrl = YES;
    return [self beforeController];
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(HBReadSubController *)viewController {
    self.clickPageCtrl = YES;
    return [self afterController];
}

- (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation {
    UIViewController *currentViewController = pageViewController.viewControllers.firstObject;
    if (currentViewController) {
        NSArray *viewControllers = @[currentViewController];
        [self.pageCtrl setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
        self.pageCtrl.doubleSided = NO;
        return UIPageViewControllerSpineLocationMin;
    }
    return UIPageViewControllerSpineLocationNone;
}

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed{
    self.clickPageCtrl = NO;
    [self currentController:(HBReadSubController *)self.pageCtrl.viewControllers.firstObject];
    NSLog(@"didFinishAnimating");
}

#pragma mark - TRReadCoverViewDelegate 切换页面
//切换是否完成
- (void)coverController:(HBReadCoverController *)coverController currentController:(HBReadSubController *)currentController finish:(BOOL)isFinish{
    [self currentController:currentController];
}

//获取上一个控制器
-(UIViewController *)coverController:(HBReadCoverController *)coverController getAboveControllerWithCurrentController:(UIViewController *)currentController{
    ///第一章第一页
    if (self.pageIndex <= 0 && self.chapter <= 0) {
        [self createFengMianView];
        return  nil;
    }else{
        return [self beforeController];
    }
}

//获取上下个控制器
-(UIViewController *)coverController:(HBReadCoverController *)coverController getBelowControllerWithCurrentController:(UIViewController *)currentController{
    return [self afterController];
}
- (void)currentController:(HBReadSubController *)currentController{
    if (self.pageIndex != currentController.pageIndex) {
        self.pageIndex = currentController.pageIndex;
    }
    if (self.chapter != currentController.chapter) {
        self.chapter = currentController.chapter;
        [self getchapterModel:self.chapter hasNext:NO];
    }
}
#pragma mark - HBReadBottomViewDelegate
///点击底部菜单的上一章，下一章按钮
-(void)bottomClickLastNext:(HBReadBottomView *)enumView hasLast:(BOOL)hasLast {
    if (self.chapter == 0 && hasLast) {
        [HBToast simple:WSLocalized(@"已经是第一章")];
        return;
    }
    if (self.chapterModel.next_chapter_id < 1 && !hasLast){
        [HBToast simple:WSLocalized(@"已经是最后一章")];
        return;
    }
    hasLast ? self.chapter -- : self.chapter ++;
    self.pageIndex = 0;
    if (hasLast) {
        [self showChapterData:YES];
    }else{
        [self showChapterData:NO];
    }
    [self reloadData];
}
///設置
- (void)bottomClickSeeting:(HBReadBottomView *)enumView {
    [self.mangerView showSetView];
}

///点击底部菜单的阅读进度滑动
-(void)bottomSliderPageChange:(HBReadBottomView *)enumView pageControl:(NSInteger)pageControl {
    self.pageIndex = pageControl;
    [self reloadUI];
}

///白天夜间模式切换
-(void)bottomChangeDayNight:(HBReadBottomView *)enumView ifDay:(BOOL)ifDay {
    [[HBReadSettingManager shared] setNightWithIfNight:ifDay];
    [self resetDataView:NO];
    [self.mangerView reloadData];
}

///展示章节列表
- (void)bottomChapterList:(HBReadBottomView *)enumView {
    self.novelModel.chapter_id = self.chapterModel.id;
    [ViewManager showChapterVCWithNovel:self.novelModel selectHandle:^(HBChapterModel * obj) {
        [self loadChapterDetailWithID:obj.id lineNum:0 hasFirst:NO];
    } inController:self];
}

#pragma mark - HBReadSettingViewDelegate
///改变字体
- (void)readSeetingWithSeetingView:(HBReadSettingView *)seetingView changeFont:(NSInteger)font {
    [self resetDataView:NO];
}
///改变翻页样式
- (void)readSeetingWithSeetingView:(HBReadSettingView *)seetingView changeBrowState:(HBBrowseType)state {
    self.pagecurl ? [self loadPageUI] : [self loadCoverUI];
    [self reloadData];
}

///改变背景色
-(void)readSeetingWithSeetingView:(HBReadSettingView *)seetingView changeSkinState:(HBReadColor)skinType {
    ///如果是夜间。则变为白天
    HBReadSettingModel *model = [[HBReadSettingManager shared] showModel];
    if (model.night){
        model.night = NO;
        [[HBReadSettingManager shared] setNightWithIfNight:NO];
        [self.mangerView reloadData];
    }
    [self resetDataView:NO];
}

///改变行间距
- (void)readSeetingWithSeetingView:(HBReadSettingView *)seetingView changeLineSpacing:(NSInteger)lineSpacing {
    [self resetDataView:NO];
}

#pragma mark GRPayControllerDelegate
- (void)payControllerPayActionWithChapter:(HBChapterModel *)chapter num:(NSInteger)num {
    [HBEvenManager event:@"chapter_purchase" evenLogType:(HBEvenLogType_Click)];
    if (num == 1) {
        [self payRequest:chapter isAuto:NO];
    }
    else {
        [self packagePayRequest:chapter num:num];
    }
}

- (void)payControllerRechargeActionWithChapter:(HBChapterModel *)chapter {
    [ViewManager pushCoinVCWithChapter:chapter inController:self];
    [HBEvenManager event:@"Storage_value" evenLogType:(HBEvenLogType_Click)];
}

- (HBReadManageView *)mangerView{
    if (!_mangerView) {
        _mangerView = [[HBReadManageView alloc]initWithFrame:CGRectMake(0, 0, HBScreenWidth, HBScreenHeight)];
        _mangerView.delegate = self;
        _mangerView.enumView.delegate = self;
        _mangerView.setView.delegate = self;
        WeakSelf
        _mangerView.navView.backBtnBlock = ^{
            [weakSelf backAction];
        };
    }
    return _mangerView;
}

- (void)setPageIndex:(NSInteger)pageIndex{
    _pageIndex = pageIndex;
    self.mangerView.enumView.sliderView.value = pageIndex;
}
@end
